package com.iot.lemon.web;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.iot.lemon.model.TOrder;
import com.iot.lemon.service.TOrderService;
import com.iot.lemon.util.UserUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;
import top.ibase4j.core.base.AppBaseController;
import top.ibase4j.core.support.pay.WxPayment;
import top.ibase4j.core.util.InstanceUtil;
import top.ibase4j.core.util.WebUtil;

/**
 * <p>
 * 订单  前端控制器
 * </p>
 *
 * @author ShenHuaJie
 * @since 2018-09-19
 */
@Controller
@RequestMapping("/app/order")
@Api(value = "订单接口", description = "订单接口")
public class TOrderController extends AppBaseController<TOrder, TOrderService> {
    @RequestMapping(value = "/read/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "查询订单", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object query(HttpServletRequest request,
        @RequestHeader("token") @ApiParam(value = "token", required = true) String token, String keyword) {
        Map<String, Object> param = WebUtil.getParameter(request);
        param.put("villageId", UserUtil.getMyVillageId(request));
        param.put("orderBy", "biz_type, order_time");
        return super.query(param);
    }

    @RequestMapping(value = "/read/detail", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "订单详情", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object get(HttpServletRequest request,
        @RequestHeader("token") @ApiParam(value = "token", required = true) String token, Long id) {
        TOrder param = WebUtil.getParameter(request, TOrder.class);
        param.setVillageId(UserUtil.getMyVillageId(request));
        return super.get(param);
    }

    @PostMapping
    @ApiOperation(value = "修改订单", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object update(HttpServletRequest request,
        @RequestHeader("token") @ApiParam(value = "token", required = true) String token, @ApiParam("订单id") Long id,
        @ApiParam("支付方式：1微信，2支付宝") String payType, String remark) {
        TOrder param = WebUtil.getParameter(request, TOrder.class);
        param.setOrgaId(UserUtil.getMyOrgaId(request));
        param.setVillageId(UserUtil.getMyVillageId(request));
        Long userId = getCurrUser(request);
        if (param.getId() == null) {
            param.setCreateBy(userId);
            param.setCreateTime(new Date());
        }
        param.setUpdateBy(userId);
        param.setUpdateTime(new Date());
        Object record = service.updateOrder(param);
        Map<String, Object> result = InstanceUtil.newHashMap("bizeCode", 1);
        result.put("record", record);
        return setSuccessModelMap(result);
    }

    @RequestMapping(value = "wxPayReturn.api", method = {RequestMethod.POST})
    @ApiOperation(value = "微信回调", notes = "微信回调接口", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiIgnore
    public Object wxPayReturn(HttpServletRequest request) {
        Map<String, String> result = InstanceUtil.newHashMap("return_code", "<![CDATA[SUCCESS]]>");
        try {
            Map<String, Object> param = WebUtil.getParameter(request);
            Assert.notNull(param.get("appid"), "应用APPID不能为空.");
            Assert.notNull(param.get("mch_id"), "商户号不能为空.");
            service.updateWxPayReturn(param);
        } catch (Exception e) {
            logger.error("", e);
            result = InstanceUtil.newHashMap("return_code", "<![CDATA[FAIL]]>");
            result.put("return_msg", "<![CDATA[" + e.getMessage() + "]]>");
        }
        logger.info(JSON.toJSONString(result));
        return ResponseEntity.ok(WxPayment.toXml(result));
    }

    @RequestMapping(value = "aliPayReturn.api", method = {RequestMethod.POST})
    @ApiOperation(value = "支付宝回调", notes = "支付宝回调接口", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiIgnore
    public Object aliPayReturn(HttpServletRequest request) {
        Map<String, String> result = InstanceUtil.newHashMap("msg", "SUCCESS");
        try {
            Map<String, Object> param = WebUtil.getParameter(request);
            Assert.notNull(param.get("app_id"), "应用APPID不能为空.");
            Assert.notNull(param.get("out_trade_no"), "商户号不能为空.");
            service.updateAliPayReturn(param);
        } catch (Exception e) {
            logger.error("", e);
            result = InstanceUtil.newHashMap("msg", "erorr");
        }
        logger.info(JSON.toJSONString(result));
        return ResponseEntity.ok(result);
    }
}
